<template>
  <div class="medical-record-detail">
    <el-card shadow="never">
      <template #header>
        <div class="card-header">
          <h2>医疗记录详情</h2>
          <el-button @click="goBack">
            <el-icon><ArrowLeft /></el-icon> 返回
          </el-button>
        </div>
      </template>

      <div v-loading="loading">
        <!-- 医疗记录基本信息 -->
        <el-card v-if="medicalRecord" class="record-card" shadow="never">
          <template #header>
            <h3 class="section-title">
              <el-icon><Document /></el-icon>
              医疗记录
            </h3>
          </template>
          
          <el-descriptions :column="2" border>
            <el-descriptions-item label="记录编号">{{ medicalRecord.recordId }}</el-descriptions-item>
            <el-descriptions-item label="就诊日期">{{ formatDate(medicalRecord.visitDate) }}</el-descriptions-item>
            <el-descriptions-item label="患者姓名">{{ medicalRecord.patientInfo?.name || '未知' }}</el-descriptions-item>
            <el-descriptions-item label="医生姓名">{{ medicalRecord.doctorInfo?.name || '未知' }}</el-descriptions-item>
            <el-descriptions-item label="科室">{{ medicalRecord.departmentInfo?.name || '未知' }}</el-descriptions-item>
            <el-descriptions-item label="状态">
              <el-tag :type="getStatusType(medicalRecord.status)">{{ medicalRecord.status }}</el-tag>
            </el-descriptions-item>
          </el-descriptions>
          
          <el-divider />
          
          <el-row :gutter="20">
            <el-col :span="12">
              <h4>主诉</h4>
              <p>{{ medicalRecord.chiefComplaint || '无' }}</p>
              
              <h4>现病史</h4>
              <p>{{ medicalRecord.presentIllness || '无' }}</p>
              
              <h4>既往史</h4>
              <p>{{ medicalRecord.pastHistory || '无' }}</p>
            </el-col>
            <el-col :span="12">
              <h4>体格检查</h4>
              <ul v-if="medicalRecord.physicalExam">
                <li v-if="medicalRecord.physicalExam.bloodPressure">血压：{{ medicalRecord.physicalExam.bloodPressure }}</li>
                <li v-if="medicalRecord.physicalExam.pulse">脉搏：{{ medicalRecord.physicalExam.pulse }}</li>
                <li v-if="medicalRecord.physicalExam.temperature">体温：{{ medicalRecord.physicalExam.temperature }}</li>
                <li v-if="medicalRecord.physicalExam.height">身高：{{ medicalRecord.physicalExam.height }}</li>
                <li v-if="medicalRecord.physicalExam.weight">体重：{{ medicalRecord.physicalExam.weight }}</li>
              </ul>
              <p v-else>无体格检查记录</p>
            </el-col>
          </el-row>
          
          <el-divider />
          
          <h4>诊断结果</h4>
          <div v-if="medicalRecord.diagnosis && medicalRecord.diagnosis.length > 0">
            <el-tag 
              v-for="(diag, index) in medicalRecord.diagnosis" 
              :key="index"
              type="primary"
              class="diagnosis-tag"
            >
              {{ diag.name }} ({{ diag.type }})
            </el-tag>
          </div>
          <p v-else>无诊断记录</p>
          
          <h4>治疗方案</h4>
          <p>{{ medicalRecord.treatmentPlan || '无' }}</p>
        </el-card>

        <!-- 关联的处方 -->
        <el-card class="related-card" shadow="never">
          <template #header>
            <h3 class="section-title">
              <el-icon><Notebook /></el-icon>
              关联处方 ({{ relatedData.prescriptions?.total || 0 }})
            </h3>
          </template>
          
          <div v-if="relatedData.prescriptions?.items?.length > 0">
            <el-card 
              v-for="prescription in relatedData.prescriptions.items" 
              :key="prescription.id"
              class="prescription-card"
              shadow="hover"
            >
              <div class="prescription-header">
                <span class="prescription-id">处方号：{{ prescription.prescriptionId }}</span>
                <el-tag :type="getPrescriptionStatusType(prescription.status)">
                  {{ prescription.status }}
                </el-tag>
              </div>
              
              <el-divider />
              
              <h5>诊断</h5>
              <div v-if="prescription.diagnosis?.length > 0" class="diagnosis-list">
                <el-tag 
                  v-for="(diag, index) in prescription.diagnosis" 
                  :key="index"
                  size="small"
                  class="diagnosis-tag"
                >
                  {{ diag }}
                </el-tag>
              </div>
              
              <h5>药品清单</h5>
              <el-table :data="prescription.items" stripe style="width: 100%">
                <el-table-column prop="drugName" label="药品名称" />
                <el-table-column prop="specification" label="规格" />
                <el-table-column prop="dosage" label="剂量" />
                <el-table-column prop="frequency" label="频次" />
                <el-table-column prop="quantity" label="数量" />
                <el-table-column prop="days" label="天数" />
                <el-table-column prop="instructions" label="用法说明" />
              </el-table>
              
              <div v-if="prescription.remarks" class="prescription-remarks">
                <strong>备注：</strong>{{ prescription.remarks }}
              </div>
              
              <div class="prescription-time">
                开具时间：{{ formatDateTime(prescription.createdAt) }}
              </div>
            </el-card>
          </div>
          <el-empty v-else description="暂无关联处方" />
        </el-card>

        <!-- 关联的医嘱 -->
        <el-card class="related-card" shadow="never">
          <template #header>
            <h3 class="section-title">
              <el-icon><List /></el-icon>
              关联医嘱 ({{ relatedData.medicalOrders?.total || 0 }})
            </h3>
          </template>
          
          <div v-if="relatedData.medicalOrders?.items?.length > 0">
            <el-card 
              v-for="order in relatedData.medicalOrders.items" 
              :key="order.id"
              class="order-card"
              shadow="hover"
            >
              <div class="order-header">
                <span class="order-id">医嘱号：{{ order.orderId }}</span>
                <div>
                  <el-tag size="small" type="info">{{ order.type }}</el-tag>
                  <el-tag size="small" :type="getOrderStatusType(order.status)">
                    {{ order.status }}
                  </el-tag>
                  <el-tag size="small" :type="getPriorityType(order.priority)">
                    {{ order.priority }}
                  </el-tag>
                </div>
              </div>
              
              <el-divider />
              
              <h5>医嘱项目</h5>
              <div v-for="(item, index) in order.items" :key="index" class="order-item">
                <div class="item-header">
                  <el-tag size="small" type="primary">{{ item.type }}</el-tag>
                  <span v-if="item.frequency" class="frequency">{{ item.frequency }}</span>
                  <span v-if="item.duration" class="duration">{{ item.duration }}</span>
                </div>
                <div class="item-content">{{ item.content }}</div>
                <div v-if="item.note" class="item-note">备注：{{ item.note }}</div>
              </div>
              
              <div v-if="order.note" class="order-note">
                <strong>医嘱说明：</strong>{{ order.note }}
              </div>
              
              <div class="order-time">
                开立时间：{{ formatDateTime(order.createdAt) }}
                <span v-if="order.execution?.executedAt">
                  | 执行时间：{{ formatDateTime(order.execution.executedAt) }}
                </span>
              </div>
            </el-card>
          </div>
          <el-empty v-else description="暂无关联医嘱" />
        </el-card>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { medicalRecordAPI } from '@/utils/api'
import { format } from 'date-fns'
import { ArrowLeft, Document, Notebook, List } from '@element-plus/icons-vue'

const route = useRoute()
const router = useRouter()
const loading = ref(false)
const medicalRecord = ref(null)
const relatedData = ref({
  prescriptions: { total: 0, items: [] },
  medicalOrders: { total: 0, items: [] }
})

// 获取医疗记录ID
const recordId = route.params.id

// 获取医疗记录详情
const getMedicalRecordDetail = async () => {
  if (!recordId) {
    ElMessage.error('医疗记录ID无效')
    return
  }

  loading.value = true
  try {
    console.log('获取医疗记录详情，ID:', recordId)
    
    // 获取医疗记录基本信息
    const recordRes = await medicalRecordAPI.getMedicalRecord(recordId)
    if (recordRes.success && recordRes.data) {
      medicalRecord.value = recordRes.data
      console.log('医疗记录详情:', recordRes.data)
    } else {
      throw new Error(recordRes.message || '获取医疗记录失败')
    }
    
    // 获取关联的处方和医嘱
    const relatedRes = await medicalRecordAPI.getRelatedData(recordId)
    if (relatedRes.success && relatedRes.data) {
      relatedData.value = relatedRes.data
      console.log('关联数据:', relatedRes.data)
    } else {
      console.warn('获取关联数据失败:', relatedRes.message)
    }
    
  } catch (error) {
    console.error('获取医疗记录详情失败:', error)
    ElMessage.error('获取医疗记录详情失败：' + (error.message || '网络错误'))
  } finally {
    loading.value = false
  }
}

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return ''
  try {
    return format(new Date(dateStr), 'yyyy-MM-dd')
  } catch (e) {
    return dateStr
  }
}

// 格式化日期时间
const formatDateTime = (dateStr) => {
  if (!dateStr) return ''
  try {
    return format(new Date(dateStr), 'yyyy-MM-dd HH:mm:ss')
  } catch (e) {
    return dateStr
  }
}

// 获取状态类型
const getStatusType = (status) => {
  const types = {
    '草稿': 'info',
    '已完成': 'success',
    '已签名': 'warning'
  }
  return types[status] || 'info'
}

// 获取处方状态类型
const getPrescriptionStatusType = (status) => {
  const types = {
    '待审核': 'warning',
    '已审核': 'primary',
    '已发药': 'success',
    '已取消': 'danger'
  }
  return types[status] || 'info'
}

// 获取医嘱状态类型
const getOrderStatusType = (status) => {
  const types = {
    '已开立': 'primary',
    '已执行': 'success',
    '已停止': 'danger'
  }
  return types[status] || 'info'
}

// 获取优先级类型
const getPriorityType = (priority) => {
  const types = {
    '常规': '',
    '加急': 'warning',
    '紧急': 'danger'
  }
  return types[priority] || ''
}

// 返回
const goBack = () => {
  router.go(-1)
}

// 页面加载时获取数据
onMounted(() => {
  getMedicalRecordDetail()
})
</script>

<style scoped>
.medical-record-detail {
  width: 100%;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.section-title {
  margin: 0;
  color: #409eff;
  font-size: 16px;
  font-weight: 600;
  display: flex;
  align-items: center;
  gap: 8px;
}

.record-card {
  margin-bottom: 20px;
}

.related-card {
  margin-bottom: 20px;
}

.prescription-card,
.order-card {
  margin-bottom: 15px;
}

.prescription-header,
.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.prescription-id,
.order-id {
  font-weight: 600;
  color: #409eff;
}

.diagnosis-tag {
  margin-right: 8px;
  margin-bottom: 8px;
}

.diagnosis-list {
  margin-bottom: 15px;
}

.prescription-remarks,
.order-note {
  margin-top: 15px;
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.prescription-time,
.order-time {
  margin-top: 15px;
  color: #999;
  font-size: 12px;
}

.order-item {
  margin-bottom: 15px;
  padding: 10px;
  background-color: #fafbfc;
  border-radius: 4px;
  border-left: 3px solid #409eff;
}

.item-header {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 8px;
}

.frequency,
.duration {
  font-size: 12px;
  color: #666;
}

.item-content {
  margin-bottom: 8px;
  line-height: 1.6;
}

.item-note {
  font-size: 12px;
  color: #999;
}

h4, h5 {
  margin-top: 20px;
  margin-bottom: 10px;
  color: #333;
}

h4:first-of-type {
  margin-top: 0;
}

ul {
  padding-left: 20px;
}

li {
  margin-bottom: 5px;
}
</style> 